var searchResultsGraphic;
var searchresultGraphicLayer;
var searchResults;
var searchResultClicked;
function zoomToSearchResults(result) {
	if (typeof searchresultGraphicLayer === 'undefined') {
            searchresultGraphicLayer = new esri.layers.GraphicsLayer({id:"searchresultGraphicLayer"});
        }
        map.addLayer(searchresultGraphicLayer);
        searchresultGraphicLayer.clear();
        addSearchResultGraphic(result);
        if (result.geometry.type === 'point') {
            map.centerAndZoom(result.geometry, 7);
        }
        else {
            map.centerAndZoom(result.geometry.getExtent().getCenter(), 7);
        }
        searchresultGraphicLayer.show();
        searchResultClicked = result;
}

function addSearchResultGraphic(result) {
    //  This was used to show polygons instead of point symbols.
    
    //searchresultGraphicLayer.add(new esri.Graphic(result.geometry, symbol));
    
    
    if (result.geometry.type === 'polygon') {
        var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0,0,128]), 2), new dojo.Color([0,0,128,0.4]));
        searchresultGraphicLayer.add(new esri.Graphic(result.geometry, symbol));
        textGeometry = result.geometry.getExtent().getCenter().offset(0,result.geometry.getExtent().getHeight()*(.51));
    }
    if (result.geometry.type === 'point') {
        var symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 10, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0,0,128]), 2), new dojo.Color([0,0,128,0.4]));
        searchresultGraphicLayer.add(new esri.Graphic(result.geometry, symbol));
        textGeometry = result.geometry.offset(0,25);
    }
    
    
    //add a text symbol to the location
    var displayText = result.location;
    var font = new esri.symbol.Font("16pt",esri.symbol.Font.STYLE_NORMAL, esri.symbol.Font.VARIANT_NORMAL,esri.symbol.Font.WEIGHT_BOLD,"Helvetica");

    var textSymbol = new esri.symbol.TextSymbol(displayText,font,new dojo.Color("black"));
    //textSymbol.setOffset(0,result.geometry.getExtent().getHeight());
    
    searchresultGraphicLayer.add(new esri.Graphic(textGeometry, textSymbol));

}
function formatSearchResults(category, results) {
	var output = '';
	var location = '';
        searchResults[category] = new Array();
	for (i=0; i < results['results'][category]['count']; i++) {
		if ((i % 2) > 0) {
			var bgColor = '#E8E8E8';
		}
		else {
			var bgColor = 'white';
		}
		var r = results['results'][category][i];
		if (r['geometry'] != null && r['geometry'] != 'null') {
			if (r['location'] != r['label']) {
				location = "<br /><font style='font-size:75%;'><i>("+r['location']+")</i></font>";
			}
                        
			var geometry = 	parseGeometry(r['geometry']);
		//extent = geometry.getExtent();
			output=output+"<div style='margin:0;padding:0;width:100%; background:"+bgColor+";'><a href='#' onClick=\"zoomToSearchResults(searchResults['"+category+"']['"+i+"'])\">"+r['label']+"</a>"+location+"</div>";
			
            r['geometry'] = geometry;            
            searchResults[category][i] = r;
		}
		else {
			output=output+"<div style='margin:0;padding:0;width:100%; background:"+bgColor+";'>"+r['label']+"<br /><font style='font-size:75%;'><i>(Location Currently Unavailable)</i></font></div>";
		}				
	}
	return(output);
}
var aContainer;
function showSearchResults (results) {
        dojo.byId('searchResultMessage').innerHTML = '';
	searchResults = new Array;
        dojo.byId('searchResultsExampleDiv').style.visibility = 'hidden';
        
        if (typeof aContainer !== 'undefined') {
            aContainer.destroyRecursive(true);
            aContainer = new dijit.layout.AccordionContainer({style:"width: 99%; height:100%"}, "searchResultsDiv");
        }
        else {           
            aContainer = new dijit.layout.AccordionContainer({style:"width: 99%; height:100%"}, "searchResultsDiv");
        }
        //if (aContainer.hasChildren() == true) {
        //    dojo.forEach(aContainer.getChildren(), function(child){
        //       alert(child);
        //    });
        //    aContainer.destroyRecursive();
        //    aContainer.destroyRendering();
        //    aContainer.destroyDescendants();
        //}
        
	var output = '';
	if (results['total_count'] > 0) {
		console.log('Total Results: '+results['total_count']+'.');
                
                aContainer.addChild(new dijit.layout.ContentPane({
                            id:'resultsTitle',
                            title: "Total Results ("+results['total_count']+")",
                            content: 'Click one of the categories below to see the results.'
                        }));
		
		
		if (typeof results['results']['building'] === "object" && results['results']['building']['count'] > 0) {
                        console.log('Buildings found: '+results['results']['building']['count']);
                        aContainer.addChild(new dijit.layout.ContentPane({
                            id:'buildingAccordionPane',
                            title: "Buildings ("+results['results']['building']['count']+")",
                            content: formatSearchResults('building',results)
                        }));
			//output=output+'<div style="padding-bottom:10px;"><b>Buildings:</b><br />'
			//output=output+formatSearchResults('buildings',results);
			//output=output+'</div>';
			
		}
		if (typeof results['results']['department'] === "object" && results['results']['department']['count'] > 0) {
                        console.log('Departments found: '+results['results']['department']['count']);
                        aContainer.addChild(new dijit.layout.ContentPane({
                            id:'departmentAccordionPane',
                            title: "Departments ("+results['results']['department']['count']+")",
                            content: formatSearchResults('department',results)
                        }));
			//output=output+'<div style="padding-bottom:10px;"><b>Departments:</b><br />';
			//output=output+formatSearchResults('department',results);
			//output=output+'</div>';
			
		}		
		if (typeof results['results']['people'] === "object" && results['results']['people']['count'] > 0) {
                        console.log('People found: '+results['results']['people']['count']);            
                        aContainer.addChild(new dijit.layout.ContentPane({
                            id:'peopleAccordionPane',
                            title: "People ("+results['results']['people']['count']+")",
                            content: formatSearchResults('people',results)
                        }));
			//output=output+'<div style="padding-bottom:10px;"><b>People:</b><br />';
			//output=output+formatSearchResults('people',results);
			//output=output+'</div>';
			
		}
		if (typeof results['results']['rooms'] === "object" && results['results']['rooms']['count'] > 0) {
			//output=output+'<div style="padding-bottom:10px;"><b>Rooms:</b><br />';
			//output=output+formatSearchResults('rooms',results);		
			//output=output+'</div>';
			console.log('Rooms found: '+results['results']['rooms']['count']);
                        aContainer.addChild(new dijit.layout.ContentPane({
                            id:'roomsAccordionPane',
                            title: "Rooms ("+results['results']['rooms']['count']+")",
                            content: formatSearchResults('rooms',results)
                        }));
		}
		if (typeof results['results']['class'] === "object" && results['results']['class']['count'] > 0) {
			//output=output+'<div style="padding-bottom:10px;"><b>Classes (Excluding Sections):</b><br />';
			//output=output+formatSearchResults('class',results);		
			//output=output+'</div>';
			console.log('Classes found: '+results['results']['class']['count']);
                        aContainer.addChild(new dijit.layout.ContentPane({
                            id:'classAccordionPane',
                            title: "Classes ("+results['results']['class']['count']+")",
                            content: formatSearchResults('class',results)
                        }));
		}
		if (typeof results['results']['campusservice'] === "object" && results['results']['campusservice']['count'] > 0) {
			//output=output+'<div style="padding-bottom:10px;"><b>Campus Services:</b><br />';
			//output=output+formatSearchResults('campusservice',results);		
			//output=output+'</div>';
			console.log('Campus Services found: '+results['results']['campusservice']['count']);
                        aContainer.addChild(new dijit.layout.ContentPane({
                            id:'campusserviceAccordionPane',
                            title: "Campus Services ("+results['results']['campusservice']['count']+")",
                            content: formatSearchResults('campusservice',results)
                        }));
		}
        if (typeof results['results']['parking'] === "object" && results['results']['parking']['count'] > 0) {
			//output=output+'<div style="padding-bottom:10px;"><b>Campus Services:</b><br />';
			//output=output+formatSearchResults('campusservice',results);		
			//output=output+'</div>';
			console.log('Parking Areas found: '+results['results']['parking']['count']);
                        aContainer.addChild(new dijit.layout.ContentPane({
                            id:'parkingAccordionPane',
                            title: "Parking Areas ("+results['results']['parking']['count']+")",
                            content: formatSearchResults('parking',results)
                        }));
		}                
		if (typeof results['results']['foodestablishments'] === "object" && results['results']['foodestablishments']['count'] > 0) {
			//output=output+'<div style="padding-bottom:10px;"><b>Campus Services:</b><br />';
			//output=output+formatSearchResults('campusservice',results);		
			//output=output+'</div>';
			console.log('Food Establishments found: '+results['results']['foodestablishments']['count']);
                        aContainer.addChild(new dijit.layout.ContentPane({
                            id:'foodestablishmentsAccordionPane',
                            title: "Food Establishments ("+results['results']['foodestablishments']['count']+")",
                            content: formatSearchResults('foodestablishments',results)
                        }));
		}
		output=output+'<br /><i><font style="font-size:75%">**Please note:  Locations may not be accurate.  This search module is not meant to be an authoritative source for locations.<br /><b>If a location is incorrect, <A HREF="mailto:bryan@geog.ucsb.edu?Subject=%5BICM%5D%20%20Missing%20/%20Incorrect%20Location&Body=Additional%20comments%20%28optional%2C%20but%20helpful%29%3A%0A%0A%0A%3D%3D%3D%3DREPORT%20%5BDO%20NOT%20EDIT%2C%20AUTOMATICALLY%20GENERATED%5D%3D%3D%3D%3D%0ASearch%20Text%3A%20%22'+dojo.byId('searchBox').value+'%22%0AVARDUMP%0A%3D%3D%3D%3DEND%20AUTOMATICALLY%20GENERATED%20REPORT%3D%3D%3D%3D%0A">please report it</A>.</font></i></b>';
		//dojo.byId('searchResultsDiv').innerHTML = output;
	}
	else {
		//dojo.xhrGet({
		//	// The URL to request
		//	url: "/api.php?action=searchboxSearch&expandedSearch=1&searchText="+box.get('value'),
		//	handleAs: "json",
		//	// The method that handles the request's successful result
		//	// Handle the response any way you'd like!
		//    load: showSearchResults
		//});
		dojo.byId('searchResultMessage').innerHTML = '<br /><b>No Results Found</b><br />Try rephrasing your search.<br /><br />';
                dojo.byId('searchResultsExampleDiv').style.visibility = 'visible';
	}
	//alert(output);
        //dojo.byId('searchResultsDiv').innerHTML = '';
        
        //if (aContainer_started != true) {
            aContainer.startup();
        //}
}
function initSearchModule_v2() {
	dojo.ready(function(){
    var form = dijit.byId('searchForm');
    var box  = dijit.byId('searchBox');
    
    var submit = function(event) {
        dojo.stopEvent(event);
		dojo.xhrGet({
			// The URL to request
			url: "/api.php?action=searchboxSearch&searchText="+box.get('value'),
			handleAs: "json",
			// The method that handles the request's successful result
			// Handle the response any way you'd like!
		    load: showSearchResults
		});
    };
        
    dojo.connect(form, 'onSubmit', submit);
	});
}